#include <math.h>
#include <stdio.h>
#include <stdlib.h>

#include "../include/camera.h"

Camera::Camera() {
	d = 256;
	s = 1;
}
//w = Eye -Look / |Eye-Look|
//u = Up x w / |Up x w|
//v= wx u

//Vertex Eye;
//Vector Look;
//Vector Up;
void Camera::orthonormal() {
	w.set((Eye.x - Look.x), (Eye.y - Look.y), (Eye.z - Look.z));
	u = Up.cross(w);
	v = w.cross(u);
}

Ray Camera::generatePrimaryRay(int x1, int y1, int width1, int height1) {
	double x = (double) x1;
	double y = (double) y1;
	double width = (double) width1;
	double height = (double) height1;
	int n = 4;
	//	D=xvu+yvv-dw
	Ray ray;
	// Calculate a primary ray
	ray.P.set(Eye.x, Eye.y, Eye.z, 1.0);
	//xv = s(c - width/2), yv = s(r - height/2)
//	double xv = (x/width)-0.5;
	double xv = s * (x - width / 2);
//	double yv = (y/height)-0.5;
	double yv = s * (y - height / 2);


	//D=xv*u+yv*v-d*w
	//ab = (ax*bx, ay*by, az*bz)
	Vector temp1 = u.multiply(xv);
	Vector temp2 = v.multiply(yv);
	Vector temp3 = w.multiply(d);
	Vector temp4 = temp1.add(temp2);
	Vector D = temp4.subtract(temp3);

	ray.D.set(D.x, D.y, D.z);
	ray.D.normalise();

	return ray;
}
float getRandFloat() {
	int x;
	float f;

	x = rand();
	f = (float) (x & 0xffff);
	f = f / 65536.0;

	return f;
}

//RayTracing + anti alias
Colour Camera::PrimaryRayTracing(int x1, int y1, int width1, int height1,Scene * scene) {
	double x = (double) x1;
	double y = (double) y1;
	double width = (double) width1;
	double height = (double) height1;
	//	D=xvu+yvv-dw
	Ray ray;
	// Calculate a primary ray
	ray.P.set(Eye.x, Eye.y, Eye.z, 1.0);
	//xv = s(c - width/2), yv = s(r - height/2)
	//double xv = (x/width)-0.5;

	Colour col;
	col.clear();
	int n = 3;
	for (int p = 0; p < n; p++) {
		for (int q = 0; q < n; q++) { // across pixel
//			double xv = s * (x - width / 2 + getRandFloat());
//			double yv = s * (y - height / 2 + getRandFloat());
			double xv = s * (x - width / 2 + (q + 0.5) / n);
			double yv = s * (y - height / 2 + (p + 0.5) / n);

			Vector temp1 = u.multiply(xv);
			Vector temp2 = v.multiply(yv);
			Vector temp3 = w.multiply(d);
			Vector temp4 = temp1.add(temp2);
			Vector D = temp4.subtract(temp3);

			ray.D.set(D.x, D.y, D.z);
			ray.D.normalise();

			Colour coltemp = scene->raytrace(ray, 8);

			col.red = col.red + coltemp.red;
			col.green = col.green + coltemp.green;
			col.blue = col.blue + coltemp.blue;
		}
	}
	col.red = col.red/n/n;
	col.green = col.green/n/n;
	col.blue = col.blue/n/n;
	return col;
}

